from django.contrib.auth.backends import ModelBackend
from .models import User
import re


def jwt_response_payload_handler(token, user=None, request=None):
    """
    重写JWT登入后的响应视图
    源码在 /usr/local/lib/python3.9/site-packages/rest_framework_jwt/utils.py
    :param token:
    :param user:
    :param request:
    :return:
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


# 多账号登入
def get_user_by_account(account):
    """
    通过传入的用户名或者手机号，获取模型对象
    :param account: 手机号或者用户名
    :return: 返回user模型或者none
    """
    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.get(phone=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user

class UserNamePhoneAuthBackend(ModelBackend):
    """
    修改jwt登入，默认只能使用username，现在调整为username和phone
    注意：需要修改配置项
    """
    # username可能是手机号
    def authenticate(self, request, username=None, password=None, **kwargs):

        # 获取user
        user = get_user_by_account(username)

        # 判断user密码是否OK，条件是user存在且密码正确。
        if user and user.check_password(password):
            # 响应到前端
            return user